package day8;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author oldliu
 * @since 1.0
 */
public class Taker extends Thread {
    private final Account ac;
    private static Lock lock = new ReentrantLock();

    public Taker(String name, Account ac) {
        super(name);
        this.ac = ac;
    }

    @Override
    public void run() {
        Random r = new Random();
        while (ac.getMoney() > 0) {
            int m = r.nextInt(200);
            System.out.println(this.getName() + "打算取钱：" + m + "元");
            //synchronized (ac) {

            try {
                lock.lock();
                if (ac.getMoney() >= m) {
                    try {
                        sleep(m);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    this.ac.withDraw(m);

                    System.out.println(this.getName() + "打算取钱：" + m + "元成功，余额是" + ac.getMoney() + "元");
                } else {
                    System.out.println(this.getName() + "打算取钱：" + m + "元,钱不够了");
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
            // }

        }
        System.out.println("余额是" + ac.getMoney() + "元");
    }
}
